<%@ page import="xyz.qduwo.entity.UserEntity" %><%--
  Created by IntelliJ IDEA.
  User: gen3
  Date: 2020/4/9
  Time: 11:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String username = (String) session.getAttribute("user");
    String roomid = (String) session.getAttribute("con_num");
%>
<html lang="en">
<head>
    <title>黑板</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
    <link rel="stylesheet" href="css/bootstrap-combined.min.css">
    <link href="css/toastr.css">
    <script src="js/toastr.min.js"></script>
    <script src="js/glimpse.js"></script>
    <script src="js/glimpse.toastr.js"></script>
    <link href="css/canvas.css" rel="stylesheet">
    <script src="js/colorpicker.js"></script>
    <script>
        var $toastlast;
        var roomid="<%=roomid %>"//房间名
        var nickname = "<%=username %>";//自己的昵称
        var flag = "join";
        var info = flag + "|" +roomid + "|" +nickname;
        var websocket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            console.log("Websocket握手开始")
            let url = "ws://${pageContext.request.getServerName()}:${pageContext.request.getServerPort()}${pageContext.request.contextPath}/websocket/"+info
            console.log(url)
            websocket = new WebSocket(url);
            //websocket = new WebSocket("ws://localhost:8080/StreamingBoard_war_exploded/websocket");
        } else {
            alert('当前浏览器 Not support websocket')
        }

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            // console.log("收到远程数据" + innerHTML);
            toastr.success(innerHTML);
        }

        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
        }

        //发送消息
        function send(message) {
            websocket.send(message);
            console.log("发送成功")
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("WebSocket连接发生错误");
        };

        //连接成功建立的回调方法
        websocket.onopen = function () {
            setMessageInnerHTML("WebSocket连接成功");
        };

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            let data = JSON.parse(event.data);
            console.log(data);
            let content = data["content"];
            let user = data["nickname"];
            let flag = data["flag"];
            let date = data["date"];

            let self_tag =data["isSelf"];
            if(flag=="enterroom"){
                let message = undefined;
                try{
                    message =data["message"];
                }finally {
                    if (message){
                        setMessageInnerHTML(message);
                    }
                }
                if (content instanceof Array) {
                    content.forEach(el => {
                        setMessageInnerHTML(el);
                        remote_draw(el);
                    })
                    console.log("加载数据成功")
                } else {
                    setMessageInnerHTML(content);
                    remote_draw(content);
                }
            }
            if(true){
                if(!self_tag){ //过滤掉自己发的信息
                    let message = undefined;
                    try{
                        message =data["message"];
                    }finally {
                        if (message){
                            setMessageInnerHTML(message);
                        }
                    }
                    if (content instanceof Array) {
                        content.forEach(el => {
                            setMessageInnerHTML(el);
                            remote_draw(el);
                        })
                        console.log("加载数据成功")
                    } else {
                        setMessageInnerHTML(content);
                        remote_draw(content);
                    }
                }

            }
        };

        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("远程服务器终止了连接");
        };

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            send(JSON.stringify({		//退出房间
                nickname:nickname,
                flag:"exitroom",
                roomid:roomid
            }));
            closeWebSocket();
        }
    </script>
    <style>
        .toast-center-center {

            position: absolute;
            z-index: 99999;
        }
    </style>
</head>
<script>
    $(function () {
        var canva = $('#canvas');
        canva.attr("width", $(window).get(0).innerWidth)
        canva.attr("height", $(window).get(0).innerHeight)

    });
</script>

<body>
<%--画布--%>
<canvas width="" height="" id="canvas" class="draw-container"></canvas>
<img src="icons/chalk.png">
<%--蒙层--%>
<div class="hidden-layer" onclick='$(".adjust-line-weight-toolbar").hide();$(".hidden-layer").hide();'></div>
<%--调整画笔粗细对话框--%>
<div class="adjust-line-weight-toolbar">
    <input type="range" min="1" max="40" value="1" id="linechange" onchange="change_lineweight()"/>
</div>
<%--工具箱--%>
<div class="tool-bar">
    <div class="tool-bar-header">
        工具箱
    </div>
    <a onclick="changetool(0)">粉笔</a>
    <a onclick="changetool(1)">直线</a>
    <a onclick="changetool(2)">矩形</a>
    <a onclick="changetool(3)">圆</a>
    <a onclick="changetool(4)">橡皮</a>
    <a onclick="changetool(5)">激光笔</a>
    <div id="color-picker" style="width: 90%;height: 32px;"></div>
    <a id="linewidth" onclick='$(".hidden-layer").show();show_model(".adjust-line-weight-toolbar")'>1px</a>
    <a onclick="upload_image()">保存</a>
</div>

</body>
<script>
    toastr.options = {
        "closeButton": false, //是否显示关闭按钮

        "debug": false, //是否使用debug模式

        "positionClass": "toast-center-center",//弹出窗的位置

        "showDuration": "300",//显示的动画时间

        "hideDuration": "1000",//消失的动画时间

        "timeOut": "5000", //展现时间

        "extendedTimeOut": "1000",//加长展示时间

        "showEasing": "swing",//显示时的动画缓冲方式

        "hideEasing": "linear",//消失时的动画缓冲方式

        "showMethod": "fadeIn",//显示时的动画方式

        "hideMethod": "fadeOut" //消失时的动画方式
    };
    //显示远程鼠标
    function draw_remote_cursor_single(type, top, left, username) {
        let cursor_type;
        if (type == 4) {
            cursor_type = "icons/eraser.png";
        } else {
            cursor_type = "icons/chalk.png";
        }
        let tpl = "<div id=\"" + username + "\" class=\"remote-cursor\" style=\"top:" + top + "px;left: " + left + "px\"><img src=\"" + cursor_type + "\"><div>" + username + "</div></div>";
        $('body').append(tpl);
        setTimeout(function () {
            document.getElementById(username).remove();
        }, 200); //200秒为远程鼠标的显示时间
    }

    function draw_remote_cursor(type, username, points) {
        draw_remote_cursor_single(type, points[0]["y"], points[0]["x"], username);
        draw_remote_cursor_single(type, points[points.length - 1]["y"], points[points.length - 1]["x"], username);
    }
</script>
<script>
    function remote_draw(tpl) {
        console.log("开始远程绘制");
        let user = tpl["user"];
        let tool = parseInt(tpl["type"]);
        let linewidth = tpl["linewidth"];
        let colorvalue = tpl["colorvalue"];
        let points = tpl["points"];
        switch (tool) {
            case 0:
                remote_drawpencil(linewidth, colorvalue, points);
                if (colorvalue == "#ffffff") {
                    draw_remote_cursor(4, user, points);
                } else {
                    draw_remote_cursor(0, user, points);
                }
                break;
            case 1:
                remote_drawLine(linewidth, colorvalue, points);
                draw_remote_cursor(1, user, points);
                break;
            case 2:
                remote_drawRect(linewidth, colorvalue, points);
                draw_remote_cursor(2, user, points);
                break;
            case 3:
                remote_drawCircle(linewidth, colorvalue, points);
                draw_remote_cursor(3, user, points);
                break;
        }
        console.log("远程绘制结束");
    }

    function remote_drawpencil_single(x, y, pre_x, pre_y) {
        // loadImage(0);
        // let ctx = document.getElementById('canvas').getContext('2d');
        ctx.beginPath();
        ctx.moveTo(pre_x, pre_y);
        ctx.lineTo(x, y);
        ctx.stroke();

    }

    function remote_drawpencil(lineweight, linecolorhex, points) {
        let ctx = document.getElementById('canvas').getContext('2d');
        ctx.lineWidth = lineweight;
        ctx.strokeStyle = linecolorhex;

        for (let i = 0; i < points.length; i++) {
            if (i === 0)
                continue;
            else {
                remote_drawpencil_single(points[i]["x"], points[i]["y"], points[i - 1]["x"], points[i - 1]["y"])
            }
        }
        ;


    }

    function remote_drawLine(lineweight, linecolorhex, points) {
        // loadImage(1);
        let ctx = document.getElementById('canvas').getContext('2d');
        ctx.lineWidth = lineweight;
        ctx.strokeStyle = linecolorhex;
        ctx.beginPath();
        ctx.moveTo(points[0]["x"], points[0]["y"]);
        ctx.lineTo(points[1]["x"], points[1]["y"]);
        ctx.stroke();
    }

    function remote_drawRect(lineweight, linecolorhex, points) {
        // loadImage(2);
        let ctx = document.getElementById('canvas').getContext('2d');
        ctx.lineWidth = lineweight;
        ctx.strokeStyle = linecolorhex;
        ctx.beginPath();
        ctx.strokeRect(points[0]["x"], points[0]["y"], points[1]["x"] - points[0]["x"], points[1]["y"] - points[0]["y"]);
    }

    function remote_drawCircle(lineweight, linecolorhex, points) {
        // loadImage(3);
        let ctx = document.getElementById('canvas').getContext('2d');
        ctx.lineWidth = lineweight;
        ctx.strokeStyle = linecolorhex;
        ctx.beginPath();
        var rx = (points[1]["x"] - points[0]["x"]) / 2;
        var ry = (points[1]["y"] - points[0]["y"]) / 2;
        var r = Math.sqrt(rx * rx + ry * ry);
        ctx.arc(rx + points[0]["x"], ry + points[0]["y"], r, 0, Math.PI * 2); // 第5个参数默认是false-顺时针
        ctx.stroke();
    }
</script>
<script>
    var linecolorhex = "#000000"; //画笔颜色
    var lineweight = 1; //默认笔触大小
    $(".adjust-line-weight-toolbar").hide();
    $(".hidden-layer").hide();
    $(document).ready(
        Colorpicker.create({
            el: "color-picker",
            color: "#000000",
            change: function (elem, hex) {
                console.log("取色器颜色变化" + hex);
                elem.style.backgroundColor = hex;
                linecolorhex = hex;

            }
        })
    );
</script>
<script>
    var tool = 0 //0-粉笔 1-直线 2-矩形 3-圆 4-橡皮 5-激光笔
    var canvas = document.getElementById('canvas'); // 得到画布
    var ctx = canvas.getContext('2d'); // 得到画布的上下文对象
    ctx.imageSmoothingEnabled = true; //抗锯齿
    var scale = $(window).get(0).devicePixelRatio; //scale
    let height = $(window).get(0).innerHeight;
    let width = $(window).get(0).innerWidth;
    canvas.height = height * scale;
    canvas.width = width * scale;
    ctx.scale(scale, scale);

    var flag = false; //下笔
    var x = 0; // 鼠标开始移动的位置X
    var y = 0; // 鼠标开始移动的位置Y
    var url = ''; // canvas图片的二进制格式转为dataURL格式
    var points = new Array();  //储存笔迹坐标
    /* 为canvas绑定mouse事件 */
    $('canvas').mousedown(function (e) {
        flag = true;
        x = e.offsetX; // 鼠标落下时的X
        y = e.offsetY; // 鼠标落下时的Y
    }).mouseup(function (e) {
        switch (tool) {
            case 0:
                sync(0, points, linecolorhex);
                console.log("绘制画笔");
                break;
            case 1:
                drawLine(e, true);
                break;
            case 2:
                drawRect(e, true);
                break;
            case 3:
                drawCircle(e, true);
                break;
            case 4:
                sync(0, points, "#ffffff");
        }
        points = [];
        flag = false;
        url = $('canvas')[0].toDataURL(); // 每次 mouseup 都保存一次画布状态
    }).mousemove(function (e) {
        //实时渲染
        switch (tool) {
            case 0:
                drawPencil(e, 0);
                break;
            case 1:
                drawLine(e);
                break;
            case 2:
                drawRect(e);
                break;
            case 3:
                drawCircle(e);
                break;
            case 4:
                drawPencil(e, 4);
                break;
        }
    });
</script>
<script>
    //更改笔触大小
    function change_lineweight() {
        lineweight = $("#linechange").val();
        console.log("画笔粗细改变" + lineweight);
        $("#linewidth").html(lineweight + "px");
    }

    //切换工具
    function changetool(value) {
        tool = value;
        switch (tool) {
            case 0:
                console.log("切换到画笔");
                document.getElementById('canvas').style.cursor = 'url("./icons/chalk.png"),help';
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                console.log("切换到橡皮");
                document.getElementById('canvas').style.cursor = 'url("./icons/eraser.png"),help';
                break;
            case 5:
                console.log("切换到激光笔");
                document.getElementById('canvas').style.cursor = 'url("./icons/laser_pointer.png"),help';
        }
    }

    //画笔工具和橡皮工具
    function drawPencil(e, state = 4) {
        // loadImage(0);
        if (state == 4)
            ctx.strokeStyle = "#ffffff";
        else
            ctx.strokeStyle = linecolorhex;
        if (flag) {
            ctx.lineWidth = lineweight;
            ctx.lineTo(e.offsetX, e.offsetY);
            //ctx.closePath(); //放射状效果
            ctx.stroke(); // 调用绘制方法
            points.push({
                x: e.offsetX,
                y: e.offsetY
            });
        } else {
            x = e.offsetX; // 鼠标落下时的X
            y = e.offsetY; // 鼠标落下时的Y
            ctx.beginPath();
            ctx.moveTo(x, y);
        }
    }

    //画矩形
    function drawRect(e, state = false) {
        if (flag) {
            ctx.lineWidth = lineweight;
            ctx.strokeStyle = linecolorhex;
            loadImage(2);
            ctx.beginPath();
            ctx.strokeRect(x, y, e.offsetX - x, e.offsetY - y);
            if (state) {
                points.push({
                    x: x,
                    y: y
                });
                points.push({
                    x: e.offsetX,
                    y: e.offsetY
                });
                console.log("绘制矩形 " + x + " " + y + " " + e.offsetX + " " + e.offsetY);
                sync(2, points, linecolorhex);
            }
        }
    }

    //画直线
    function drawLine(e, state = false) {
        if (flag) {
            ctx.lineWidth = lineweight;
            ctx.strokeStyle = linecolorhex;
            loadImage(1);
            ctx.beginPath();
            ctx.moveTo(x, y);
            ctx.lineTo(e.offsetX, e.offsetY);
            ctx.stroke();
            if (state) {
                points.push({
                    x: x,
                    y: y
                });
                points.push({
                    x: e.offsetX,
                    y: e.offsetY
                });
                sync(1, points, linecolorhex);
                console.log("绘制直线 " + x + " " + y + " " + e.offsetX + " " + e.offsetY);
            }
        }
    }

    //画圆
    function drawCircle(e, state = false) {
        if (flag) {
            ctx.lineWidth = lineweight;
            ctx.strokeStyle = linecolorhex;
            loadImage(3);
            ctx.beginPath();
            var rx = (e.offsetX - x) / 2;
            var ry = (e.offsetY - y) / 2;
            var r = Math.sqrt(rx * rx + ry * ry);
            ctx.arc(rx + x, ry + y, r, 0, Math.PI * 2); // 第5个参数默认是false-顺时针
            ctx.stroke();
            if (state) {
                points.push({
                    x: x,
                    y: y
                });
                points.push({
                    x: e.offsetX,
                    y: e.offsetY
                });
                console.log("绘制圆 " + x + " " + y + " " + e.offsetX + " " + e.offsetY);
                sync(3, points, linecolorhex);
            }

        }
    }

    //load image(从本地或者云端加载数据)
    function loadImage(tool = tool, img = url) {
        if ((tool != 0) || (tool != 4)) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }
        let im1 = new Image();
        im1.src = url;
        ctx.drawImage(im1, 0, 0, canvas.width, canvas.height);
    }

    //保存画布
    function upload_image() {
        return document.getElementById("canvas").toDataURL("image/png");
    }

    //点击屏蔽
    function name(params) {

    }

    $(window).resize(function () {
        var canva = $('#canvas');
        canva.attr("width", $(window).get(0).innerWidth);
        canva.attr("height", $(window).get(0).innerHeight);
        loadImage();
    });

</script>

<script>
    //显示笔触宽模态窗
    function show_model(id) {
        let top = parseInt($("#linewidth").offset().top) + 2;
        let left = parseInt($("#linewidth").offset().left) + 2;
        $(id).offset().top = top + "px";
        $(id).offset().left = left + "px";
        $(id).show();
    }

    function sync(type, points, color) {
        /*推送数据*/
        var message_tpl = {
            user: "<%=username %>",
            type: type,
            colorvalue: color,
            points: points,
            linewidth: lineweight
        }
        var operation = {			//加入房间时的欢迎消息
            nickname:nickname,    //用户名
            content:message_tpl,		//消息内容
            target:roomid,		//推送到目标房间
            flag:"draw"};	//推送标识



        send(JSON.stringify(operation));
    }
    //上传图片
    function upload() {
        canvas.toBlob(function (blob) {
            $.ajax(
                {
                    url:"./canvasServlet",
                    type:"post",
                    data: blob,
                    contentType: false,
                    processData: false,
                    success: function(data) {
                        if (data.type == "success") {
                            setMessageInnerHTML("上传成功");
                        } else {
                            alert(data.msg);
                        }
                    },
                    error:function(data) {
                        alert("上传失败")
                    }
                }
            )
        }, 'image/jpeg', 0.9)



    }
</script>

</html>
